import React from 'react';
import { Modal, Form, Select, Input, Button, message } from 'antd';
import type { ProductTemplateFormValues } from '../../types/device';

const { Option } = Select;

interface ProductTemplateModalProps {
  visible: boolean;
  onCancel: () => void;
  onSave: (values: ProductTemplateFormValues) => void;
}

/**
 * 产品模板模态框组件
 * 用于选择产品模板和设置从机地址
 */
const ProductTemplateModal: React.FC<ProductTemplateModalProps> = ({ visible, onCancel, onSave }) => {
  const [form] = Form.useForm();

  // 模拟产品模板数据
  const productTemplates = [
    { value: 'template-1', label: '智能传感器模板' },
    { value: 'template-2', label: '控制器模板' },
    { value: 'template-3', label: '网关设备模板' },
    { value: 'template-4', label: '执行器模板' },
  ];

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        onSave(values);
        message.success('产品模板设置成功');
        form.resetFields();
      })
      .catch(info => {
        message.error('表单验证失败，请检查输入');
      });
  };

  // 处理模态框关闭
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title="设置产品模板"
      open={visible}
      onCancel={handleCancel}
      footer={null}
      width={500}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{}}
      >
        <Form.Item
          name="productTemplate"
          label="产品模板"
          rules={[{ required: true, message: '请选择产品模板' }]}
        >
          <Select placeholder="请选择产品模板">
            {productTemplates.map(template => (
              <Option key={template.value} value={template.value}>
                {template.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="slaveAddress"
          label="从机地址"
          rules={[
            { required: true, message: '请输入从机地址' },
            { pattern: /^\d+$/, message: '从机地址必须为数字' }
          ]}
        >
          <Input placeholder="请输入从机地址" />
        </Form.Item>

        <Form.Item style={{ textAlign: 'right', marginTop: 24 }}>
          <Button onClick={handleCancel} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ProductTemplateModal;